import 'package:dio/dio.dart';
import 'package:flutter_enjoy/constans/index.dart';
import 'package:flutter_enjoy/utils/toast.dart';

class RequestDio {
  final Dio _dio = Dio();
  RequestDio() {
    //请求根路径
    _dio.options.baseUrl = GlobalVariable.BASE_URL;
    //设置连接时间
    _dio.options.connectTimeout =
        Duration(seconds: GlobalVariable.NET_WORK_TIME);
    //设置接收超时时间
    _dio.options.receiveTimeout =
        Duration(seconds: GlobalVariable.NET_WORK_TIME);

    // 添加拦截器
    _interceptors();
  }
  //拦截器
  void _interceptors() {
    _dio.interceptors.add(InterceptorsWrapper(
      // 请求拦截
      onRequest: (options, handler) {
        // TODO 添加token
        handler.next(options);
      },
      // 响应拦截
      onResponse: (response, handler) {
        // TODO 提取后端数据
        // TODO HTTP业务状态码判断
        // TODO 业务状态码判断
        handler.next(response);
      },
      onError: (error, handler) {
        // TODO 其他错误处理
        PromptAction.showError(error.response?.data['message'] ?? '请求失败');
        handler.next(error);
      },
    ));
  }

  // 请求方法二次封装
  Future get(String url, {Map<String, dynamic> params = const {}}) async {
    final response = await _dio.get(url, queryParameters: params);
    return _handleResponse(response);
  }

  Future post(String url, {Map<String, dynamic> data = const {}}) async {
    final response = await _dio.post(url, data: data);
    return _handleResponse(response);
  }

  Future put(String url, {Map<String, dynamic> data = const {}}) async {
    final response = await _dio.put(url, data: data);
    return _handleResponse(response);
  }

  Future delete(String url, {Map<String, dynamic> data = const {}}) async {
    final response = await _dio.delete(url, data: data);
    return _handleResponse(response);
  }

  Future patch(String url, {Map<String, dynamic> data = const {}}) async {
    final response = await _dio.patch(url, data: data);
    return _handleResponse(response);
  }
  // 处理响应
  _handleResponse(Response response) {
    if (response.data['code'] == GlobalVariable.SUCCESS_CODE) {
      return response.data['data'];
    }else{
      PromptAction.showError(response.data['message'] ?? '业务异常');
    }
    throw Exception(response.data['message']);
  }
}

// 单例(单个实例)模式
final requestDio = RequestDio();
